﻿using System;
using System.IO;
using System.Threading.Tasks;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Provider;
using Android.Util;
using dCamera.demo;
using Java.IO;
using Android.App;
using Environment = Android.OS.Environment;
using File = Java.IO.File;
using Uri = Android.Net.Uri;

namespace GBU.Platform
{
    public class CameraHelper
    {
       // private static File _file;
        private static File _dir;

        private static int ResizeHeight = 1600;
        private static int ResizeWidth = 1200;

        public static double WhRate = 0.75;

        //public static void TakePhotoCamera(Context context)
        //{
        //    CreateDirectoryForPictures();

        //    Intent i = new Intent(MediaStore.ActionImageCapture);

        //    _file = new File(_dir, string.Format("myPic_{0}.jpg", DateTime.Now.ToString("yyyyMMddHHmmssfff")));

        //    var uri = Uri.FromFile(_file);
        //    i.PutExtra(MediaStore.ExtraOutput, uri);
        //    ((Activity)context).StartActivityForResult(i, GlobalConsts.CapturePic);
        //}

        static void CreateDirectoryForPictures()
        {
            //_file = new File(_dir, string.Format("t_{0}.jpg", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
            _dir = DeviceHelper.GetCreatePicDirectory();
        }

        //public static void OnTakePhotoResult(int requestCode, Result resultCode, Intent data,Context context,Action<string> callback)
        //{

        //   // base.OnActivityResult(requestCode, resultCode, data);
        //    //int h = imgTakeImg.Height;
        //    //int w = imgTakeImg.Width;

        //    if (resultCode == Result.Ok)
        //    {
        //        switch (requestCode)
        //        {
        //            case GlobalConsts.CapturePic:
        //                PostToAlbum(context);

        //                if (callback != null)
        //                {
        //                    callback(_file.Path);
        //                }
        //                //using (Bitmap img = _file.Path.LoadAndResizeBitmap(w, h))
        //                //{
        //                //    imgTakeImg.SetImageBitmap(img);
        //                //}
        //                break;
        //            case GlobalConsts.SelectPic:

        //                var path = data.Data.ToImageFilePath(context.ContentResolver);

        //                if (callback != null)
        //                {
        //                    callback(_file.Path);
        //                }
        //               // _file = new File(path);
        //                // imgTakeImg.SetImageURI(data.Data);

        //                //using (Bitmap img = _file.Path.LoadAndResizeBitmap(w, h))
        //                //{
        //                //    imgTakeImg.SetImageBitmap(img);
        //                //}
        //                break;
        //            default:
        //                break;
        //        }

        //    }
        //}

        private static void PostToAlbum(Context context,File file)
        {
            Intent mediascanIntent = new Intent(Intent.ActionMediaScannerScanFile);
            var contenturi = Uri.FromFile(file);
            mediascanIntent.SetData(contenturi);
            context.SendBroadcast(mediascanIntent);
        }

        public static File SaveToSdCard(Context context,byte[] data)
        {
            _dir = DeviceHelper.GetCreatePicDirectory();
           var  _file = new File(_dir, string.Format("t_{0}.jpg", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
            using (var fs = new FileOutputStream(_file))
            {
                fs.Write(data);
            }

            //notify system album
            PostToAlbum(context,_file);
            return _file;
        }

        public static File SaveToSdCardAndResize(Context context, byte[] data,WarterMarkLocation warterLoc=null)
        {
            _dir = DeviceHelper.GetCreatePicDirectory();
            var _file = new File(_dir, string.Format("t_{0}.jpg", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
            var mybitmap = LoadAndResizeBitmap(data, ResizeWidth, ResizeHeight);

            if (warterLoc != null)
            {
               mybitmap= AddWarterToBitmap(context, mybitmap, warterLoc);
            }

            using (var fs = new FileStream(_file.AbsolutePath, FileMode.CreateNew))
            {
                mybitmap.Compress(Bitmap.CompressFormat.Jpeg, 80, fs);
                fs.Flush(true);
                mybitmap.Recycle();
            }

            //notify system album
            PostToAlbum(context, _file);
            return _file;
        }

        public static Bitmap LoadAndResizeBitmap(byte[] imgData, int width, int height)
        {
            // First we get the the dimensions of the file on disk
            BitmapFactory.Options options = new BitmapFactory.Options { InJustDecodeBounds = true };
            BitmapFactory.DecodeByteArray(imgData, 0, imgData.Length, options);

            // Next we calculate the ratio that we need to resize the image by
            // in order to fit the requested dimensions.
            int outHeight = options.OutHeight;
            int outWidth = options.OutWidth;
            int inSampleSize = 1;

            if (outHeight > height || outWidth > width)
            {
                inSampleSize = outWidth > outHeight
                                   ? outHeight / height
                                   : outWidth / width;
            }

            // Now we will load the image and have BitmapFactory resize it for us.
            options.InSampleSize = inSampleSize;
            options.InJustDecodeBounds = false;
            Bitmap resizedBitmap = BitmapFactory.DecodeByteArray(imgData, 0, imgData.Length, options);
            return resizedBitmap;
        }

        public static Task<File> SaveToSdCardAsync(Context context, byte[] data)
        {
           return  Task.Factory.StartNew(() =>
            {
               return SaveToSdCard(context,data);
            });
        }
        public static Task<File> ResizeSaveToSdCardAsync(Context context, byte[] data,WarterMarkLocation warterLoc=null)
        {
            return Task.Factory.StartNew(() =>
            {
                return SaveToSdCardAndResize(context, data, warterLoc);
            });
        }

        public static Task<File> SaveToSdCardAsync( Bitmap bitmap)
        {
            return Task.Factory.StartNew(() =>
            {
                return saveBitmap(bitmap);
            });
        }

        public  static File saveBitmap(Bitmap bitmap)
        {
            _dir = DeviceHelper.GetCreatePicDirectory();
            var _file = new File(_dir, string.Format("cat_{0}.png", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
            try
            {
                using (var fs = new FileStream(_file.AbsolutePath, FileMode.CreateNew))
                {
                    //Bitmap.CreateScaledBitmap()
                    //bitmap.EraseColor(Color.Black);
                    bitmap.Compress(Bitmap.CompressFormat.Png, 85, fs);
                   
                    fs.Flush(true);
                    
                }
                bitmap.Recycle();
            }
            catch (Exception ex)
            {
                Log.Debug("CameraHelper:ss:", ex.Message);
            }
            return _file;
        }

        public static Bitmap AddWarterToBitmap(Context context, Bitmap target,WarterMarkLocation warterLoc)
        {
            var warter = BitmapFactory.DecodeResource(context.Resources, warterLoc.WarterPicId);
            Bitmap newImg = Bitmap.CreateBitmap(target.Width, target.Height, Bitmap.Config.Argb8888);

            Canvas cv=new Canvas(newImg);
            cv.DrawBitmap(target,0,0,null);

            cv.DrawBitmap(warter,warterLoc.X,warterLoc.Y,null);
            cv.Save(SaveFlags.All);
            cv.Restore();
            warter.Recycle();
            return newImg;
        }
    }
}
